from flask import Flask
from Day10.models import db, User, Article, ArticleContent

app = Flask(__name__)
class Config(object):
    SQLALCHEMY_DATABASE_URI = 'mysql://root:mysql@127.0.0.1/toutiao'
    SQLALCHEMY_TRACK_MODIFICATIONS = False

app.config.from_object(Config)
db.init_app(app)

@app.route('/issue_article/<int:user_id>')
def issue_article(user_id):
    """
    发布文章
    :param user_id:
    :return:
    """
    # 为了测试方便,从数据库查一条文章数据
    article_obj = Article.query.first()
    content_obj = ArticleContent.query.get(article_obj.id)
    # user_id发布文章
    user_article = Article(
        user_id=user_id,
        channel_id=article_obj.channel_id,
        title=article_obj.title,
        cover=article_obj.cover,
        is_advertising=article_obj.is_advertising,
        ctime=article_obj.ctime,
        status=article_obj.status,
        reviewer_id=article_obj.reviewer_id,
        review_time=article_obj.review_time,
        delete_time=article_obj.delete_time,
        comment_count=article_obj.comment_count,
        allow_comment=article_obj.allow_comment,
        reject_reason=article_obj.reject_reason,
        utime=article_obj.utime
    )
    db.session.add(user_article)
    # 把sql发送到mysql中执行,并没有commit
    db.session.flush()
    user_content = ArticleContent(
        id=user_article.id,
        content=content_obj.content
    )
    db.session.add(user_content)
    # db.session.commit()
    user = User.query.get(user_id)
    user.article_count = user.article_count + 1
    db.session.add(user)
    db.session.commit()
    # 视图中默认会加上db.seesion.rollback()
    return '发布成功'

@app.route('/article_count/<int:user_id>')
def article_count(user_id):
    """
    获取用户发布文章数量
    :param user_id:
    :return:
    """
    user = User.query.get(user_id)
    return str(user.article_count)

if __name__== '__main__':
    app.run(host='192.168.226.129', debug=True)
    